
# !/usr/bin/env python
from twisted.internet import ssl, reactor,threads
from twisted.web import server, resource
from storage import *
from twisted.web import resource
from twisted.internet.threads import deferToThread
import base64
import json
import binascii
import traceback
from logger import logger
from constant import *

class NBIotServer(resource.Resource):
    isLeaf = True

    def __init__(self, storageTag):
        self.storageTag = storageTag
        self.mysqlDb = storageTag.mysqlDb
        self.data_decode = storageTag.data_decode

        logger.info("NBIotServer init!!!!")
    def print_string2hex(self, stringData):
        try:
            send_data = ""
            for k, count in enumerate(stringData):
                hexstr = binascii.b2a_hex(count)
                send_data = "%s%s"%(send_data,hexstr)
            logger.info("Data %s" % (send_data))
        except Exception,e:
            logger.error("print_string2hex error: %s"% str(e))


    def device_added_request(self, request):
        try:
            """
            logger.info(str(request))
            result, decode_json = UnPackData.get_json_format(request)
            if result == False:
                return True

            if decode_json.has_key('notifyType') \
                    and decode_json.has_key('deviceInfo') \
                    and decode_json.has_key('deviceId') \
                    and decode_json['notifyType'] == "deviceAdded":

                deviceId = decode_json['deviceId']
                deviceInfo = decode_json['deviceInfo']
                if deviceInfo.has_key('nodeId'):
                    deviceNodeId = deviceInfo['nodeId']
                    logger.info(deviceId)
                    logger.info(deviceNodeId)
                    self.mysqlDb.create_new_lamp_nbiot(deviceId, deviceNodeId, NBIOT_TYPE)

            """
        except Exception, e:
            logger.error(traceback.format_exc())
            logger.error("device_added_request post error: %s" % str(e))
        return True

    def command_response(self, request):
        try:
            logger.info(str(request))
            result, decode_json = UnPackData.get_json_format(request)
            if result == False:
                return True

            if decode_json.has_key('notifyType') \
                    and decode_json.has_key('service') \
                    and decode_json['notifyType'] == "commandRsp":

                service_json = decode_json['service']
                if service_json.has_key('data'):
                    datamsg = service_json['data']

                    data = base64.b64decode(datamsg['rawData'])

        except Exception, e:
            logger.error(traceback.format_exc())
            logger.error("command_response post error: %s" % str(e))
        return True

    def deviceDataChangedHandler(self, request):
        try:
            logger.info(str(request))
            result, decode_json = UnPackData.get_json_format(request)
            if result == False:
                return True

            if decode_json.has_key('notifyType') \
                    and decode_json.has_key('service') \
                    and decode_json.has_key('deviceId') \
                    and decode_json['notifyType'] == "deviceDataChanged":
                deviceid = decode_json['deviceId']
                service_json = decode_json['service']
                serviceId = service_json['serviceId']
                recvdata = ''
                if service_json.has_key('data') and serviceId == 'Transmission':
                    datamsg = service_json['data']
                    recvdata = base64.b64decode(datamsg['rawData'])
                    self.storageTag.msg_buffer.append({'protype': 'nbiot', 'addr': deviceid, 'msgdata': recvdata})

        except Exception, e:
            logger.error(traceback.format_exc())
            logger.error("deviceDataChangedHandler post error: %s" % str(e))
        return True

    def bind_device_request(self, request):
        try:
            logger.info(str(request))
            result, decode_json = UnPackData.get_json_format(request)
            if result == False:
                return True

            if decode_json.has_key('notifyType') \
                    and decode_json.has_key('deviceInfo') \
                    and decode_json.has_key('deviceId') \
                    and decode_json['notifyType'] == "bindDevice":

                pass

        except Exception, e:
            logger.error(traceback.format_exc())
            logger.error("bind_device_request post error: %s" % str(e))
        return True

    def render_GET(self, request):
        return "just for test!!!"

    def render_POST(self, request):

        if request.uri == NBIOT_DEVICE_DATA_CHANGED_CALLBACK_URL:
            rcvdata = request.content.getvalue()
            deferToThread(self.deviceDataChangedHandler, rcvdata)
        if request.uri == NBIOT_ADD_DEVICE_CALLBACK_URL:
            rcvdata = request.content.getvalue()
            deferToThread(self.device_added_request, rcvdata)
        elif request.uri == NBIOT_APP_CALLBACK_URL:
            rcvdata = request.content.getvalue()
            deferToThread(self.command_response, rcvdata)
        elif request.uri == NBIOT_BIND_DEVICE_URL:
            rcvdata = request.content.getvalue()
            deferToThread(self.bind_device_request, rcvdata)

        return "OK"




#storageTag = Storage()
#server = server.Site(NBIotServer(storageTag))
#reactor.listenSSL(8080, server, ssl.DefaultOpenSSLContextFactory(
#    'cert/server.key', 'cert/server.crt'))
#reactor.run()